<template>
  <el-card style="height: 80px; margin-bottom: 10px">
    <el-form inline class="form">
      <el-form-item label="用户名">
        <el-input placeholder="请输入用户名" v-model="userName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="search"
          :disabled="userName ? false : true"
          >搜索</el-button
        >
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card>
    <el-button type="primary" @click="addUser" v-has="`btn.User.add`"
      >添加</el-button
    >
    <el-button
      type="danger"
      :disabled="SelectArr.length >= 1 ? false : true"
      @click="DeleteSelectUser"
      v-has="`btn.User.remove`"
      >批量删除</el-button
    >
    <el-table
      border
      style="margin: 10px 0px"
      :data="UserArr"
      @selection-change="selectUser"
    >
      <el-table-column
        type="selection"
        width="80px"
        align="center"
      ></el-table-column>
      <el-table-column label="#" align="center" type="index"></el-table-column>
      <el-table-column label="id" align="center" prop="id"></el-table-column>
      <el-table-column
        label="用户姓名"
        align="center"
        prop="username"
      ></el-table-column>
      <el-table-column
        label="用户名称"
        align="center"
        prop="name"
      ></el-table-column>
      <el-table-column
        label="用户角色"
        align="center"
        prop="roleName"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
      ></el-table-column>
      <el-table-column label="操作" width="300px" align="center">
        <template #="{ row }">
          <el-button
            type="primary"
            icon="user"
            size="small"
            @click="setRole(row)"
            v-has="`btn.User.assgin`"
            >分配角色</el-button
          >
          <el-button
            type="info"
            icon="Edit"
            size="small"
            @click="updateUser(row)"
            v-has="`btn.User.update`"
            >编辑</el-button
          >

          <el-popconfirm
            :title="`你确定删除${row.username}?`"
            @confirm="DeleteUserId(row)"
          >
            <template #reference>
              <el-button
                type="danger"
                icon="delete"
                size="small"
                v-has="`btn.User.remove`"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[5, 7, 9, 12]"
      background
      layout=" prev, pager, next, jumper,->,total, sizes"
      :total="totle"
      @current-change="HasUserInfo"
      @size-change="handler"
    />
  </el-card>
  <!-- 添加或者修改 -->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>{{ UserParmas.id ? "修改用户" : "添加用户" }}</h4>
    </template>
    <template #default>
      <el-form :model="UserParmas" :rules="rules" ref="forms">
        <el-form-item label="用户姓名" prop="username">
          <el-input
            placeholder="请输入用户姓名"
            v-model="UserParmas.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input
            placeholder="请输入用户昵称"
            v-model="UserParmas.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-show="!UserParmas.id">
          <el-input
            placeholder="请输入用户密码"
            v-model="UserParmas.password"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button type="primary" @click="SaveUser">确定</el-button>
      <el-button @click="cancel">取消</el-button>
    </template>
  </el-drawer>
  <!-- 分配角色 -->
  <el-drawer v-model="drawer1">
    <template #header>
      <h4>分配角色</h4>
    </template>
    <template #default>
      <el-form>
        <el-form-item label="用户名称">
          <el-input v-model="UserParmas.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="职位列表">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange(true)"
            >全部</el-checkbox
          >
          <el-checkbox-group
            v-model="UserRole"
            @change="handleCheckedCitiesChange(true)"
          >
            <el-checkbox
              v-for="(city, index) in AllRole"
              :key="index"
              :label="city"
              >{{ city.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button type="primary" @click="SaveRole">确定</el-button>
      <el-button @click="drawer1 = false">取消</el-button>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, nextTick } from "vue";
import {
  reqGetUserInfo,
  reqAddOrUpdateUser,
  reqtoAssign,
  reqDoAssignRole,
  reqDeleteUser,
  reqDeleteUserIds,
} from "@/api/acl/user/index";
import type { RoleResponesData, RoleArr } from "@/api/acl/user/type";
import { ElMessage } from "element-plus";

let pageNo = ref<number>(1);
let pageSize = ref<number>(5);
let totle = ref<number>(0);
let UserArr = ref([]);
let drawer = ref<boolean>(false);
let drawer1 = ref<boolean>(false);
//存储所有的职位信息
let AllRole = ref<RoleArr>([]);
//存储当前用户的职位信息
let UserRole = ref<any>([]);
//收集用户信息
let UserParmas = reactive<any>({
  username: "",
  name: "",
  password: "",
});
//收集用户姓名
let userName = ref<string>("");
//定义一个数组接收被选择的用户信息
let SelectArr = ref<any>([]);
//获取表单实例
let forms = ref();
//全部复选框
let checkAll = ref<boolean>(false);
//不确定因素
let isIndeterminate = ref<boolean>(false);
//获取用户信息的方法
const HasUserInfo = async (page = 1) => {
  pageNo.value = page;
  let result = await reqGetUserInfo(
    pageNo.value,
    pageSize.value,
    userName.value,
  );
  if (result.code == 200) {
    //收集数据
    totle.value = result.data.total;
    UserArr.value = result.data.records;
  }
};
//挂载时获取信息
onMounted(() => {
  HasUserInfo();
});
//总页数发生变化的回调
const handler = (size: number) => {
  pageSize.value = size;
  HasUserInfo();
};
//添加用户方法
const addUser = () => {
  //清除上一次的表单验证信息
  nextTick(() => {
    forms.value.clearValidate();
  });
  drawer.value = true;
  //清除上一次的数据
  Object.assign(UserParmas, {
    id: "",
    username: "",
    name: "",
    password: "",
  });
};
//确定按钮的回调
const SaveUser = async () => {
  //调用组件form的表单验证函数,如果返回的是一个失败的promise,则不执行后续代码
  await forms.value.validate();

  let result = await reqAddOrUpdateUser(UserParmas);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: UserParmas.id ? "修改成功" : "添加成功",
    });
    //关闭弹窗
    drawer.value = false;
    //刷新页面
    HasUserInfo(UserParmas.id ? pageNo.value : 1);
    //浏览器重新刷新一遍
    window.location.reload();
  } else {
    ElMessage({
      type: "error",
      message: UserParmas.id ? "修改失败" : "添加失败",
    });
    //关闭弹窗
    drawer.value = false;
  }
};
//修改用户的回调
const updateUser = (row: any) => {
  //收集数据
  Object.assign(UserParmas, row);
  //打开弹窗
  drawer.value = true;
  //清除上一次的用户验证信息
  nextTick(() => {
    forms.value.clearValidate();
  });
};
//取消按钮的回调
const cancel = () => {
  drawer.value = false;
};
//用户姓名验证规则
const validateUsername = (rule: any, value: string, callback: any) => {
  //解决冒红光问题，无需关注
  if (1 > 2) {
    console.log(rule);
  }
  if (value.trim().length < 5) {
    callback(new Error("用户姓名长度不能小于5"));
  } else {
    callback();
  }
};
//用户名字验证规则
const validatename = (rule: any, value: string, callback: any) => {
  //解决冒红光问题，无需关注
  if (1 > 2) {
    console.log(rule);
  }
  if (value.trim().length < 5) {
    callback(new Error("用户昵称长度不能小于5"));
  } else {
    callback();
  }
};
//用户密码验证规则
const validatePassword = (rule: any, value: string, callback: any) => {
  //解决冒红光问题，无需关注
  if (1 > 2) {
    console.log(rule);
  }
  if (value.trim().length < 6) {
    callback(new Error("用户密码长度不能小于6"));
  } else {
    callback();
  }
};
//表单验证对象
const rules = {
  username: [{ required: true, trigger: "blur", validator: validateUsername }],
  name: [{ required: true, trigger: "blur", validator: validatename }],
  password: [{ required: true, trigger: "blur", validator: validatePassword }],
};
//分配角色按钮
const setRole = async (row: any) => {
  //合并对象
  Object.assign(UserParmas, row);
  //发送请求
  let result: RoleResponesData = await reqtoAssign(UserParmas.id);
  if (result.code == 200) {
    //存储数据
    AllRole.value = result.data.allRolesList;
    UserRole.value = result.data.assignRoles;
    //判断不确定因素
    isIndeterminate.value = UserRole.value.length > 0 ? true : false;
    //显示弹窗
    drawer1.value = true;
  }
};
//顶部全选的回调
const handleCheckAllChange = (val: boolean) => {
  UserRole.value = val ? AllRole.value : [];
  isIndeterminate.value = false;
};
//底部复选框的回调
const handleCheckedCitiesChange = (value: any) => {
  isIndeterminate.value =
    value.length > 0 && value.length < AllRole.value.length;
  // UserRole.value = value;
  checkAll.value = value.length === AllRole.value.length;
};
//添加职位的回调
const SaveRole = async () => {
  let data = {
    userId: UserParmas.id,
    roleIdList: UserRole.value.map((item: any) => item.id),
  };
  //发请求
  let result = await reqDoAssignRole(data as any);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: "分配成功",
    });
    drawer1.value = false;
    //再次获取数据
    HasUserInfo(pageNo.value);
  } else {
    ElMessage({
      type: "error",
      message: "分配失败",
    });
  }
};
//删除单个用户的信息
const DeleteUserId = async (row: any) => {
  let result = await reqDeleteUser(row.id);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    //获取数据
    HasUserInfo(UserArr.value.length > 1 ? pageNo.value : pageNo.value - 1);
  }
};
//当复选框发生改变时触发
const selectUser = (value: any) => {
  SelectArr.value = value;
};
//批量删除的回调
const DeleteSelectUser = async () => {
  //整理参数
  let idList = SelectArr.value.map((item: any) => item.id);
  //发请求
  let result = await reqDeleteUserIds(idList);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    //获取数据
    HasUserInfo(UserArr.value.length > 1 ? pageNo.value : pageNo.value - 1);
  }
};
//搜索的按钮回调
const search = () => {
  //调用
  HasUserInfo();
  //清除数据
  userName.value = "";
};
//重置按钮的回调
const reset = () => {
  //调用
  HasUserInfo();
};
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
